<template>
  <div>
    <el-card class="box-card">
      <span class="demonstration">选择项目</span>
      <el-cascader
        v-model="value"
        :options="options"
        clearable
        :props="props"
        collapse-tags
        filterable
        @change="handleChange($event)"
      >
      </el-cascader>
      <span class="demonstration" style="margin-left: 50px">时间选择</span>
      <el-date-picker
        v-model="value2"
        type="month"
        placeholder="选择月"
        @change="startchange($event)"
      >
      </el-date-picker>
      <span style="color:red;font-size:16px;margin-left:50px">当前页面正在升级，预计5月21号可以正常使用</span>
      <div style="float: right">
        <div
          style="
            height: 30px;
            width: 50px;
            background: #feecbade;
            display: inline-block;
            margin-bottom: -7px;
          "
        ></div>
        <span style="margin-bottom: 5px">工时未投满</span>
        <div
          style="
            height: 30px;
            width: 50px;
            background: #eb070763;
            display: inline-block;
            margin-bottom: -7px;
          "
        ></div>
        <span>工时未投</span>
        <div
          style="
            height: 30px;
            width: 50px;
            background: #909399;
            display: inline-block;
            margin: 0 10px -7px 0;
          "
        ></div>
        <span style="margin: 0 10px 0 0">周末</span>
        <el-button type="success" @click="downLoadFn()" round>导出</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        max-height="800"
        class="tableClass"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        :header-cell-style="{ background: '#eef1f6', height: '80px' }"
        style="margin-top: 10px"
        :cell-class-name="addClass"
        :cell-style="tableCellStyle"
      >
        <el-table-column
          label="项目名称"
          width="150"
          align="center"
          fixed="left"
        >
          <template slot-scope="scope">
            {{ scope.row.project_name }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="100" align="center" fixed="left">
          <template slot-scope="scope">
            <div v-for="(v, i) in scope.row.user" :key="i">
              <div v-if="scope.row.user.length == '1'">
                {{ v.name }}
              </div>
              <div v-if="scope.row.user.length > '1'" class="borders" style="padding-top:20px">
                {{ v.name }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="部门" width="255" align="center">
          <template slot-scope="scope">
            <div v-for="(v, i) in scope.row.user" :key="i">
              <div v-if="scope.row.user.length == '1'">
                <span v-if="v.dept_1 && !v.dept_2 && !v.dept_3">
                  {{ v.dept_1 }}
                </span>
                <span v-if="v.dept_2 && !v.dept_3">
                  {{ v.dept_1 + '/' + v.dept_2 }}
                </span>
                <span v-if="v.dept_2 && v.dept_3">
                  {{ v.dept_1 + '/' + v.dept_2 + '/' + v.dept_3 }}
                </span>
              </div>
              <div
                v-if="scope.row.user.length > '1'"
                class="borders1"
                style="margin-left: -9px"
              >
                <span v-if="v.dept_1 && !v.dept_2 && !v.dept_3">
                  {{ v.dept_1 }}
                </span>
                <span v-if="v.dept_2 && !v.dept_3">
                  {{ v.dept_1 + '/' + v.dept_2 }}
                </span>
                <span v-if="v.dept_2 && v.dept_3">
                  {{ v.dept_1 + '/' + v.dept_2 + '/' + v.dept_3 }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="月份" width="100" align="center">
          <template slot-scope="scope">
            <div v-for="(v, i) in scope.row.user" :key="i">
              <div v-if="scope.row.user.length == '1'">
                {{ month }}
              </div>
              <div v-if="scope.row.user.length > '1'" class="borders" style="padding-top: 20px;">
                {{ month }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="个人小计" width="100" align="center">
          <template slot-scope="scope">
            <div v-for="(v, i) in scope.row.user" :key="i">
              <div v-if="scope.row.user.length == '1'">
                {{ v.sum_spand }}
              </div>
              <div v-if="scope.row.user.length > '1'" class="borders" style="padding-top: 20px;">
                {{ v.sum_spand }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(d, index) in daysCol"
          :key="index"
          :label="d"
          width="100"
          align="center"
          type="cell"
        >
          <template slot-scope="scope">
            <div v-for="(v, i) in scope.row.user" :key="i">
              <div v-if="scope.row.user">
                <div v-if="scope.row.user.length == '1'">
                  <div
                    v-if="v.spend_data[d] < 8 && v.spend_data[d] != 0"
                    style="background: #feecbade;width: 98px;height: 66px;margin-left: -5px;position: relative;line-height: 66px;">
                    <el-tooltip
                      placement="top"
                      effect="light"
                      style="bottom: 22px; position: absolute; left: 42px"
                    >
                      <div slot="content" v-if="v.create_name[d]">
                        {{ '分配人员' + ':' + v.create_name[d] }}
                      </div>
                      <div slot="content" v-else>{{ '分配人员 : 无' }}</div>
                      <div style="cursor: pointer">{{ v.spend_data[d] | rounding}}</div>
                    </el-tooltip>
                  </div>
                  <div v-else-if=" v.spend_data[d] == 0 && !checkWeekends.includes(d)"
                    style=" background: #eb070763; width: 98px; height: 66px; margin-left: -11px;line-height: 66px; ">
                    {{ v.spend_data[d] | rounding}}
                  </div>
                  <div v-else style="margin-left: -11px; position: relative">
                    <div v-if="!checkWeekends.includes(d)">
                      <el-tooltip placement="top" effect="light" >
                        <div slot="content" v-if="v.create_name[d]">
                          {{ '分配人员' + ':' + v.create_name[d] }}
                        </div>
                        <div slot="content" v-else>{{ '分配人员 : 无' }}</div>
                        <div style="cursor: pointer">{{ v.spend_data[d] | rounding }}</div>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
                <div v-if="scope.row.user.length > '1'" class="borders">
                  <div v-if="v.spend_data[d] < 8 && v.spend_data[d] != 0" style=" background: #feecbade; margin-left: -0px;position: relative;line-height: 26px;" class="borders">
                    <el-tooltip placement="top" effect="light" style="bottom: 22px; position: absolute; left: 44px">
                      <div slot="content" v-if="v.create_name[d]">
                        {{ '分配人员' + ':' + v.create_name[d] }}
                      </div>
                      <div slot="content" v-else>{{ '分配人员 : 无' }}</div>
                      <div style="cursor: pointer">{{ v.spend_data[d] | rounding}}</div>
                    </el-tooltip>
                  </div>
                  <div v-else-if="v.spend_data[d] == 0 && !checkWeekends.includes(d)" style="background: #eb070763;margin-left: 0px;position: relative;line-height: 62px" class="borders">
                    {{ v.spend_data[d] | rounding}}
                  </div>
                  <div v-else style="margin-left:0; position: relative">
                    <div v-if="!checkWeekends.includes(d)">
                      <el-tooltip placement="top" effect="light" style="top: 19px; position: absolute; left: 44px;">
                        <div slot="content" v-if="v.create_name[d]">
                          {{ '分配人员' + ':' + v.create_name[d] }}
                        </div>
                        <div slot="content" v-else>{{ '分配人员 : 无' }}</div>
                        <div style="cursor: pointer">{{ v.spend_data[d] | rounding}}</div>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="marT"
        background
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="baseSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 10px; margin-left: 34%"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getHeaderName } from '@/app.config';
import { DateUtil } from './utils.js';
export default {
  data() {
    return {
      tableData: [],
      loading: false,
      paramData: [],
      paramMonth: '',
      currentPage: 1,
      showMonth: '',
      daysCol: [],
      params2: {},
      value2: '',
      mon: [],
      daysCol: [],
      month: '',
      checkWeekends: [],
      value: '',
      options: [],
      props: { multiple: true },
      baseSize: 10,
      current: 1,
      total: 0,
      downProIds: [],
    };
  },
  filters: {
    rounding (value) {
      if(value || value === 0) { //这个判断是为了防止数据为空，页面渲染为NAN
        return Number(value).toFixed(1)
      }
    }
  },
  mounted() {
    this.initData();
    this.getTableData();
    this.getProList();
  },
  methods: {
    tableCellStyle(row){
      // console.log(1111,row)
      if (this.checkWeekends.includes(row.column.label)) {
        return 'background-color:#909399;padding:1px';
      }
      // arr = row.row.user.length >0  arr.map(item => {item.joinworkdate}) 入职时间 Date.parse()
      //  row.column.label 表头时间 columnIndex>4
      if(row.row.user.length > 0 && row.columnIndex>4){
        let joinTime = ''
        row.row.user.map(item => {
          joinTime =item.joinworkdate
        })
        if(Date.parse(joinTime)>Date.parse()){
          return 'background-color:#909399;padding:1px';
        }
      }
      return 'padding:1px'
    },
    addClass({ row, column, rowIndex, columnIndex }) {
      // if (this.checkWeekends.includes(column.label)) {
      //   return 'cell-grey';
      // }
    },
    downLoadFn() {
      this.loading = true;
      let downParam = {
        month: this.paramMonth,
        date: this.paramData,
        project_ids: this.downProIds,
      };
      this.$axios({
        url:
          process.env.VUE_APP_SOURSE_MANAGE_HOST +
          '/api/v1/project/get_work_hours_to_excel',
        method: 'post',
        headers: getHeaderName(),
        responseType: 'blob',
        data: downParam,
      })
        .then((res) => {
          if (res.status === 200) {
            const blob = new Blob([res.data]);
            const fileName = '工时报表.xlsx';
            // for IE
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
              // for Non-IE (chrome, firefox etc.)
              const elink = document.createElement('a');
              elink.download = fileName;
              elink.style.display = 'none';
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href);
              document.body.removeChild(elink);
              this.loading = false;
              this.$message({
                type: 'success',
                message: '导出成功!',
              });
            }
          } else {
            this.loading = false;
            this.$message.error('下载出错了!');
          }
        })
        .catch((err) => {
          this.$message.error('下载出错了!');
          this.loading = false;
        });
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getTableData();
    },
    handleChange(e) {
      let proIdArr = [];
      e.map((key) => {
        proIdArr.push(key[1]);
      });
      this.downProIds = proIdArr;
      this.params2['project_ids'] = proIdArr;
      this.current = 1;
      this.getTableData();
    },
    getProList() {
      this.$axios({
        url:
          process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/project/car_list',
        method: 'get',
        headers: getHeaderName(),
      }).then((res) => {
        this.options = res.data.data;
      });
    },
    
    startchange(e) {
      this.currentPage = 1;
      let nowTime = new Date(e);
      // let getTime = nowTime.getTime()
      let getYear = nowTime.getFullYear();
      let startData, endData, startTime, endTime;
      var Y = nowTime.getFullYear() + '-';
      var M = nowTime.getMonth() + 1;
      this.paramMonth = getYear + '-' + M;
      var D = nowTime.getDate();
      var h = nowTime.getHours() + ':';
      this.showMonth = getYear + '-' + M;
      // 前一月所在时间日期
      if (M == 1 || M == 2 || M == 4 || M == 6 || M == 8 || M == 9 || M == 11) {
        //判断31天时
        startData = new Date(nowTime - 7 * 24 * 3600 * 1000);
        let y = startData.getFullYear();
        let m = startData.getMonth() + 1;
        let d = startData.getDate();
        startTime = y + '-' + m + '-' + d;
      } else if (M == 5 || M == 7 || M == 10 || M == 12) {
        // 判断30天时
        startData = new Date(nowTime - 6 * 24 * 3600 * 1000);
        let y = startData.getFullYear();
        let m = startData.getMonth() + 1;
        let d = startData.getDate();
        startTime = y + '-' + m + '-' + d;
      }
      if (M == 3) {
        if ((getYear % 4 == 0 && getYear % 100 != 0) || getYear % 400 == 0) {
          //判断为闰年时 29
          startData = new Date(nowTime - 5 * 24 * 3600 * 1000);
          let y = startData.getFullYear();
          let m = startData.getMonth() + 1;
          let d = startData.getDate();
          startTime = y + '-' + m + '-' + d;
        } else {
          //判断为平年时 28
          startData = new Date(nowTime - 4 * 24 * 3600 * 1000);
          let y = startData.getFullYear();
          let m = startData.getMonth() + 1;
          let d = startData.getDate();
          startTime = y + '-' + m + '-' + d;
        }
      }
      // 当前月所在日期 24号
      let y1 = getYear;
      let m1 = M;
      let d1 = nowTime.getDate() + 23;
      endTime = y1 + '-' + m1 + '-' + d1;
      let dataArr = [];
      dataArr = this.getAllDate(startTime, endTime);
      let dataArr1 = [];
      let Arr3 = [];
      //循环遍历数组
      dataArr.map((val) => {
        //去掉月份前面的0
        let strArr = val.split('-');
        strArr = strArr.map(function (v) {
          if (v[0] == '0') {
            return (v = v.slice(1));
          } else {
            return v;
          }
        });
        let newVal = strArr.join('-');
        let week3 = DateUtil.datetoWeek(newVal); //this.getWeek(newVal)
        let Arr = [];
        Arr3.push(newVal);
        Arr.push(newVal, week3);
        dataArr1.push(Arr);
      });
      this.daysCol = [];
      this.daysCol = Arr3;
      this.paramData = dataArr1;
      this.mon = dataArr1;
      this.params2['page'] = this.params2.page;
      this.getTableData();
      return (this.paramData = dataArr1);
    },
    format(time) {
      let ymd = '';
      let mouth =
        time.getMonth() + 1 >= 10
          ? time.getMonth() + 1
          : '0' + (time.getMonth() + 1);
      let day = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate();
      ymd += time.getFullYear() + '-'; // 获取年份。
      ymd += mouth + '-'; // 获取月份。
      ymd += day; // 获取日。
      return ymd; // 返回日期。
    },
    getAllDate(start, end) {
      let dateArr = [];
      let startArr = start.split('-');
      let endArr = end.split('-');
      let db = new Date();
      db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2]);
      let de = new Date();
      de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2]);
      let unixDb = db.getTime();
      let unixDe = de.getTime();
      let stamp;
      const oneDay = 24 * 60 * 60 * 1000;
      for (stamp = unixDb; stamp <= unixDe; ) {
        dateArr.push(this.format(new Date(parseInt(stamp))));
        stamp = stamp + oneDay;
      }
      return dateArr;
    },
    // 默认当前月
    initData() {
      var date5 = new Date();
      var year5 = date5.getFullYear();
      var month5 = date5.getMonth() + 1;
      let day5 = date5.getDate();
      day5 > 25 ? (month5 += 1) : month5;
      var toMonth = year5 + '-' + month5;
      this.showMonth = toMonth;
      this.value2 = toMonth;
      this.paramMonth = toMonth;
      this.paramData = this.startchange1(this.value2);
      this.mon = this.paramData;
      this.daysCol = [];
      this.paramData.map((k, i) => {
        let strArr1 = k[0].split('-');
        strArr1 = strArr1.map(function (v) {
          if (v[0] == '0') {
            return (v = v.slice(1));
          } else {
            return v;
          }
        });
        let newVal1 = strArr1.join('-');
        this.daysCol.push(newVal1);
      });
    },
    getTableData() {
      this.loading = true;
      this.params2['month'] = this.paramMonth;
      this.params2['date'] = this.paramData;
      this.params2['page'] = this.current;
      this.$axios({
        url:
          process.env.VUE_APP_SOURSE_MANAGE_HOST +
          '/api/v1/project/get_work_hours',
        method: 'post',
        headers: getHeaderName(),
        data: this.params2,
      }).then((res) => {
        if (res.data.code === 200) {
          this.loading = false;
          this.tableData = res.data.data.data;
          this.month = res.data.data.month;
          this.checkWeekends = res.data.data.weekend_list;
          this.total = res.data.data.totalCount;
        }
      });
    },
    initData() {
      var date5 = new Date();
      var year5 = date5.getFullYear();
      var month5 = date5.getMonth() + 1;
      let day5 = date5.getDate();
      day5 > 25 ? (month5 += 1) : month5;
      var toMonth = year5 + '-' + month5;
      this.showMonth = toMonth;
      this.value2 = toMonth;
      this.paramMonth = toMonth;
      this.paramData = this.startchange1(this.value2);
      this.mon = this.paramData;
      this.daysCol = [];
      this.paramData.map((k, i) => {
        let strArr1 = k[0].split('-');
        strArr1 = strArr1.map(function (v) {
          if (v[0] == '0') {
            return (v = v.slice(1));
          } else {
            return v;
          }
        });
        let newVal1 = strArr1.join('-');
        this.daysCol.push(newVal1);
      });
    },
    startchange1(e) {
      this.currentPage = 1;
      let nowTime = new Date(e);
      let getYear = nowTime.getFullYear();
      let startData, endData, startTime, endTime;
      var Y = nowTime.getFullYear() + '-';
      var M = nowTime.getMonth() + 1;
      this.paramMonth = getYear + '-' + M;
      var D = nowTime.getDate();
      var h = nowTime.getHours() + ':';

      // 前一月所在时间日期
      if (M == 1 || M == 2 || M == 4 || M == 6 || M == 8 || M == 9 || M == 11) {
        //判断31天时
        startData = new Date(nowTime - 7 * 24 * 3600 * 1000);
        let y = startData.getFullYear();
        let m = startData.getMonth() + 1;
        let d = startData.getDate();
        startTime = y + '-' + m + '-' + d;
      } else if (M == 5 || M == 7 || M == 10 || M == 12) {
        // 判断30天时
        startData = new Date(nowTime - 6 * 24 * 3600 * 1000);
        let y = startData.getFullYear();
        let m = startData.getMonth() + 1;
        let d = startData.getDate();
        startTime = y + '-' + m + '-' + d;
      }
      if (M == 3) {
        if ((getYear % 4 == 0 && getYear % 100 != 0) || getYear % 400 == 0) {
          //判断为闰年时 29
          startData = new Date(nowTime - 5 * 24 * 3600 * 1000);
          let y = startData.getFullYear();
          let m = startData.getMonth() + 1;
          let d = startData.getDate();
          startTime = y + '-' + m + '-' + d;
        } else {
          //判断为平年时 28
          startData = new Date(nowTime - 4 * 24 * 3600 * 1000);
          let y = startData.getFullYear();
          let m = startData.getMonth() + 1;
          let d = startData.getDate();
          startTime = y + '-' + m + '-' + d;
        }
      }

      // 当前月所在日期 24号
      let y1 = getYear;
      let m1 = M;
      let d1 = nowTime.getDate() + 23;
      endTime = y1 + '-' + m1 + '-' + d1;

      let dataArr = [];
      dataArr = this.getAllDate(startTime, endTime);
      let dataArr1 = [];
      let Arr3 = [];
      //循环遍历数组
      dataArr.map((val) => {
        //去掉月份前面的0
        let strArr = val.split('-');
        strArr = strArr.map(function (v) {
          if (v[0] == '0') {
            return (v = v.slice(1));
          } else {
            return v;
          }
        });
        let newVal = strArr.join('-');
        let week3 = DateUtil.datetoWeek(newVal);
        let Arr = [];
        Arr3.push(newVal);
        Arr.push(newVal, week3);
        dataArr1.push(Arr);
      });

      this.daysCol = [];
      this.daysCol = Arr3;
      this.params2['page'] = this.params2.page;
      return (this.paramData = dataArr1);
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/.el-table__body-wrapper {
  z-index: 2;
}
/deep/ .el-table td.cell-grey {
  background-color: #909399 !important;
  color: #fff;
}
/deep/ .el-table td.cell-two {
  background-color: #eb070763 !important;
  color: #82848a;
}
/deep/ .el-table td.cell-three {
  background-color: #13ce666b !important;
  color: #82848a;
}
.borders {
  border-bottom: 1px solid #c5c4c1;
  width: 97px;
  margin-left: -10px;
  height: 67px;
//   line-height: 67px;
}
.borders1 {
  border-bottom: 1px solid #c5c4c1;
  width: 251px;
  margin-left: -10px;
  height: 67px;
  padding-top: 19px
//   line-height: 67px;
}
// .tableClass .cell{   
//     padding: 0!important;
//     height: 30px;
//     line-height: 30px!important;
//   }
/deep/.el-table tr {
    // background-color: #fff;
    height: 50px;}
</style>


